<template>
  <div class="body_">
    <div class="centered">
      <div style="width: 350px; margin: 150px auto">
        <div style="color: lightskyblue; font-size: 20px; text-align: center; padding: 30px 0">云校教育产品平台注册<br>
        </div>
        <el-form ref="form" :model="form" size="normal" :rules="rules">
          <el-form-item prop="phone" class="el-icon-user">
            <el-input placeholder="账号" clearable v-model="form.phone" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="密码" v-model="form.password" show-password />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input placeholder="确认密码" v-model="form.confirmPassword" show-password />
          </el-form-item>
          <ek-form-item>
            <div style="display: flex">
              <el-input v-model="form.validCode" style="width: 60%;" placeholder="请输入验证码"></el-input>
              <ValidCode @input="createValidCode" />
            </div>
          </ek-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%" @click="studentRegister">注册并登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button style="width: 100%" @click="gotoLogin">返回登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
   
<script>

import ValidCode from "@/views/login/ValidCode.vue";
export default {
  name: 'RegisterView',
  components: {
    ValidCode
  },
  data() {
    return {
      form: {},
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            type: 'string', message: '请输入不包含空格的字符', trigger: 'blur', transform(value) {
              if (value && value.indexOf(' ') === -1) {
                return value
              } else {
                return false
              }
            }
          },
          {
            trigger: 'blur', validator: (rule, value, callback) => {
              var passwordreg = /(?=.*\d)(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{6,10}/
              if (!passwordreg.test(value)) {
                callback(new Error('密码必须由数字、字母、特殊字符组合,请输入6-10位'))
              } else {
                callback()
              }
            }
          }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.checkNewPassword, trigger: 'blur' }
        ]
      },
      validCode: '',
      Student: {
        phone: '',
        password: '',
        confirmPassword: '',
      },

    }
  },
  methods: {
    createValidCode(data) {
      this.validCode = data
    },
    gotoLogin() {
      // 跳转登陆页面
      this.$router.push('/Login');
    },
    studentRegister() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.validCode) {
            this.$message.error("请填写验证码")
            return
          }
          if (this.form.validCode.toLowerCase() !== this.validCode.toLowerCase()) {
            this.$message.error("验证码错误")
            return
          }
          this.$http.post("/api/studentRegister", {
            phone: this.form.phone,
            password: this.form.password
          }, {
            headers: {
              'Content-Type': 'application/json'
            },
          }).then(response => {
            if (response.data.code == 0) {
              this.$message.error(response.data.message);
            }
            else {
              this.$message.success("注册成功");
              this.$http.post("/api/studentLogin", {
                        phone: this.form.phone,
                        password: this.form.password
                    }, {
                        headers: {
                            'Content-Type': 'application/json'
                        },
                    }).then(response => {
                        if (response.data.code == 1) {
                            this.$message.success("登录成功");
                            // 登录成功，将令牌存储在localStorage中
                            localStorage.setItem('jwt', response.data.data);
                            //把username传到下一个页面
                            localStorage.setItem('phone', this.form.phone);
                            this.$router.push({ path: '/index', query: { phone: this.form.phone } });
                        
                        }
                        else this.$message.error(response.data.message);
                    })
                        .catch(error => {
                            console.log(error)
                        })
            }
          })
            .catch(error => {
              console.log(error)
            })
        }
      });
    },
    checkNewPassword(rule, value, callback) {
      if (value !== this.form.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    }
  }
}
</script>
   
<style>
@import "@/style/login.css";
</style>